package com.qst.express.controller.wx;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qst.commonUtils.express.RandomUtil;
import com.qst.commonUtils.result.R;
import com.qst.express.entity.Courier;
import com.qst.express.entity.User;
import com.qst.express.entity.vo.CommonUser;
import com.qst.express.service.CourierService;
import com.qst.express.service.UserService;
import com.qst.express.utils.SMSUtil;
import com.qst.express.utils.UserUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:CoolTiger
 * @title: UserController
 * @projectName springboot-e
 * @description: TODO
 * @date:2022/10/11/17:38:43
 **/
@Api(description = "微信端-用户管理")
@RestController
@RequestMapping("/e/wx")
public class WxUserController {
    @Autowired
    private CourierService courierService;
    @Autowired
    private UserService userService;

    /**
     * 发送短信
     *
     * @param request
     * @param userPhone
     * @return
     */
    @GetMapping("/loginSms/{phone}")
    public R sendSms(HttpServletRequest request, @PathVariable(value = "phone") String userPhone) {
        String code = RandomUtil.getCode()+"";
         boolean flag = SMSUtil.loginSMS(userPhone, code);
        //模拟测试123456
        //String code = "123456";
        //boolean flag = true;
        if (flag) {
            //短信发送成功
            UserUtil.setLoginSms(request.getSession(), userPhone, code);
            System.out.println("存值时sessionid：" + request.getSession().getId());
            return R.ok().message("验证码已发送，请查收！");
        } else {
            //短信发送失败
            return R.ok().code(-1).message("验证码发送失败，请检查手机号或稍后再试");
        }
    }

    /**
     * 用户手机号码短信验证登陆或注册
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestParam("userPhone") String userPhone, @RequestParam("code") String userCode) {
        String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);
        System.out.println("取值时sessionid：" + request.getSession().getId());
        if (sysCode == null) {
            //手机号未获取短信
            return R.ok().code(-1).message("手机号码未获取短信");
        } else if (sysCode.equals(userCode)) {
            //手机号码和短信一致，登陆成功
            boolean flag = courierService.isCourierByPhone(userPhone);
            //TODO 这个判断应替换为快递员表格查询手机号的结果
            User user = new User();
            if (flag) {
                //身份为快递员
                user.setUser(false);
                //跟新快递员登陆时间
                courierService.updateLoginTime(userPhone);
                user.setUphone(userPhone);
                UserUtil.setWxUser(request.getSession(), user);
                return R.ok().code(1).message("登陆成功");
            } else {
                //身份为用户
                user.setUser(true);
                boolean flag2 = userService.isFindByPhone(userPhone);//判断是否已经注册
                if (!flag2) {
                    boolean insert2 = userService.insert2(userPhone);//进行注册
                }
                //跟新登陆时间
                userService.updateLoginTime(userPhone);
                user.setUphone(userPhone);
                UserUtil.setWxUser(request.getSession(), user);
                if (flag2) {
                    return R.ok().code(0).message("登陆成功");
                }
                return R.ok().code(0).message("注册成功");
            }
        } else {
            //验证码不一致，登陆失败
            return R.ok().code(-2).message("验证码不一致，请检查");
        }

    }

    /**
     * 权限控制，不同身份展示不同UI
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/userInfo")
    public R userInfo(HttpServletRequest request, HttpServletResponse response) {
        User user = UserUtil.getWxUser(request.getSession());
        String userPhone = UserUtil.getWxUser(request.getSession()).getUphone();
        boolean isUser = user.isUser();
        if (isUser) {//0用户1快递员
            User user2 = userService.findUserByPhone(userPhone);
            return R.ok().code(0).data("phone", user2.getUname());
        } else {
            Courier courier = courierService.findCourierByPhone(userPhone);
            return R.ok().code(1).data("phone", courier.getCname());
        }
    }

    /**
     * 个人中心用户名和图像显示
     *
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/findUserNameByPhone")
    public R findUserNameByPhone(HttpServletRequest request) {
        String userPhone = UserUtil.getWxUser(request.getSession()).getUphone();
        boolean flag = courierService.isCourierByPhone(userPhone);
        if (flag) {
            //快递员
            Courier courier = courierService.findCourierByPhone(userPhone);
            return R.ok().code(0).data("courier", courier);
        } else {
            //用户
            User user = userService.findUserByPhone(userPhone);
            return R.ok().code(1).data("user", user);
        }
    }

    /**
     * 判断用户是否认证
     *
     * @param request
     * @return
     */
    @GetMapping("/isIdentification")
    public R isIdentification(HttpServletRequest request) {
        String phone = UserUtil.getWxUser(request.getSession()).getUphone();
        boolean isCourier = courierService.isCourierByPhone(phone);
        if (isCourier) {//快递员
            boolean flag = courierService.isIdentification(phone);
            if (flag) {//已认证
                return R.ok().code(0).message("已认证");
            } else {//未认证
                return R.ok().code(-1).message("未认证");
            }
        } else {//用户
            boolean flag = userService.isIdentification(phone);
            if (flag) {//已认证
                return R.ok().code(1).message("已认证");
            } else {//未认证
                return R.ok().code(-1).message("未认证");
            }
        }
    }

    /**
     * 新用户认证
     *
     * @param request
     * @param userPhone
     * @param msgCode
     * @param userName
     * @param userPassword
     * @param userIdentify
     * @return
     */
    @PostMapping("/newUserIdetification")
    public R newUserIdetification(HttpServletRequest request, @RequestParam String userPhone,
                                  @RequestParam String msgCode,
                                  @RequestParam String userName,
                                  @RequestParam String userPassword,
                                  @RequestParam String userIdentify) {
        System.out.println(userPhone + "," + msgCode + "," + userName + "," + userPassword + "," + userIdentify);
        String phone = UserUtil.getWxUser(request.getSession()).getUphone();
        if (StringUtils.isEmpty(userPhone) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPassword) || StringUtils.isEmpty(userIdentify) || StringUtils.isEmpty(msgCode)) {
            return R.error().code(-1).message("请完善信息");
        }
        if (!userPhone.equals(phone)) {
            return R.error().code(-2).message("手机号码有误");
        }

        User u = new User();
        Courier c = new Courier();
        boolean isCourier = courierService.isCourierByPhone(userPhone);
        String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);

        if (isCourier) {//快递员
            c.setIdentify(userIdentify);
            c.setCpassword(userPassword);
            c.setCname(userName);
            c.setCphone(userPhone);
            if (sysCode == null) {//手机号码未获取短信
                return R.ok().code(1).message("手机号码未获取短信");
            } else if (sysCode.equals(msgCode)) {//手机号码和短信一致
                boolean flag = courierService.updateCourier(c);
                if (flag) {
                    return R.ok().code(0).message("认证成功");
                } else {
                    return R.ok().code(-1).message("认证失败");
                }
            }
        } else {//用户
            u.setIdentify(userIdentify);
            u.setUpassword(userPassword);
            u.setUname(userName);
            u.setUphone(userPhone);
            if (sysCode == null) {
                //手机号码未获取短信
                return R.ok().code(-1).message("手机号码未获取短信");
            } else if (sysCode.equals(msgCode)) {
                //手机号码和短信一致
                boolean flag = userService.updateUser(u);
                if (flag) {
                    return R.ok().code(0).message("认证成功");
                } else {
                    return R.ok().code(-1).message("认证失败");
                }
            } else {
                //验证码不一致
                return R.ok().code(-1).message("验证码错误");
            }
        }
        return R.error();
    }

    /**
     * 更新用户名字
     *
     * @param request
     * @return
     */
    @PostMapping("/updateUserName")
    public R UpdateUserName(HttpServletRequest request,
                            @RequestParam("userName") String userName,
                            @RequestParam("userPhone") String userPhone,
                            @RequestParam("code") String code
    ) {
        String phone = UserUtil.getWxUser(request.getSession()).getUphone();
        String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);
        if (sysCode == null) {
            //手机号未获取短信
            return R.ok().code(-1).message("手机号码未获取短信");
        } else if (sysCode.equals(code)) {
            //手机号码和短信一致，修改成功
            //User user = new User();

            boolean isCourier = courierService.isCourierByPhone(phone);
            boolean flag = false;
            if (isCourier) {//快递员
                flag = courierService.updateUserName(userPhone, userName);
            } else {//用户
                flag = userService.updateUserName(userPhone, userName);
            }
            if (flag) {
                return R.ok().code(0).message("更新成功");
            } else {
                return R.ok().code(-1).message("更新失败");
            }
        } else {
            //验证码不一致，登陆失败
            return R.ok().code(-2).message("验证码不一致，请检查");
        }

    }
}
